package com.example.aabb;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;


import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class ToActivity extends AppCompatActivity {

    private RelativeLayout rlBack;
    private RelativeLayout rl;
    private RelativeLayout rl2;

    private List<Bill> billList = new ArrayList<>();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.to_activity);
        rlBack = (RelativeLayout) findViewById(R.id.rl_back);
        rl = (RelativeLayout) findViewById(R.id.rl);
        rl2 = (RelativeLayout) findViewById(R.id.rl2);
        billList = (ArrayList) getIntent().getSerializableExtra("list");
        System.out.println("====数据=="+billList);
        rlBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        rl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                exportToPdf(ToActivity.this, billList, "bills.pdf");
            }
        });
        rl2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                exportToExcel(ToActivity.this,billList,"bills.xlsx");
            }
        });
    }

        public void exportToExcel(Context context, List<Bill> billList, String fileName) {
            Workbook workbook = new XSSFWorkbook();
            Sheet sheet = workbook.createSheet("账单详情");

            // 创建表头行
            Row headerRow = sheet.createRow(0);
            String[] headers = {"交易类型", "关联方", "金额", "交易时间"};
            for (int i = 0; i < headers.length; i++) {
                Cell cell = headerRow.createCell(i);
                cell.setCellValue(headers[i]);
            }

            // 填充账单数据
            int rowNum = 1;
            for (Bill bill : billList) {
                Row dataRow = sheet.createRow(rowNum++);
                dataRow.createCell(0).setCellValue(bill.getType());
                dataRow.createCell(1).setCellValue(bill.getFromOrTo());
                dataRow.createCell(2).setCellValue(bill.getAmount());
                dataRow.createCell(3).setCellValue(bill.getDate());
            }

            File cache = getCacheDir();
            long time = System.currentTimeMillis();
            File tempFile = new File(cache, "bills" + time + ".xlsx");

            try (FileOutputStream outputStream = new FileOutputStream(tempFile)) {
                workbook.write(outputStream);
                Toast.makeText(ToActivity.this, "成功", Toast.LENGTH_SHORT).show();
                System.out.println("====成功==");
            } catch (IOException e) {
                e.printStackTrace();
                Toast.makeText(ToActivity.this, "失败" + e.getMessage(), Toast.LENGTH_SHORT).show();
                System.out.println("====失败=="+e.getMessage());
            }
        }

    public void exportToPdf(Context context, List<Bill> billList, String fileName) {
        Document document = new Document();
        try {
            // 获取外部存储目录（同样要注意权限问题）
//            File directory = context.getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS);
            File cache = getCacheDir();
            long time = System.currentTimeMillis();
            File tempFile = new File(cache, "bills" + time + ".pdf");
//            if (directory!= null) {
//                File file = new File(directory, fileName);
                PdfWriter.getInstance(document, new FileOutputStream(tempFile));
                document.open();

                // 添加标题
                Paragraph title = new Paragraph("账单详情");
                title.setAlignment(Paragraph.ALIGN_CENTER);
                document.add(title);

                // 创建表格，4列对应账单的4个属性
                PdfPTable table = new PdfPTable(4);
                table.addCell("交易类型");
                table.addCell("关联方");
                table.addCell("金额");
                table.addCell("交易时间");

                // 填充账单数据
                for (Bill bill : billList) {
                    table.addCell(bill.getType());
                    table.addCell(bill.getFromOrTo());
                    table.addCell(String.valueOf(bill.getAmount()));
                    table.addCell(bill.getDate());
                }

                document.add(table);
                document.close();
                Toast.makeText(ToActivity.this, "成功", Toast.LENGTH_SHORT).show();
//            }
        } catch (DocumentException | IOException e) {
            e.printStackTrace();
            Toast.makeText(ToActivity.this, "失败", Toast.LENGTH_SHORT).show();
            System.out.println("====失败=="+e.getMessage());
        }
    }
}